package user

import (
	"gitee.com/cheneylau/components/web-server/controller"
	"gitee.com/cheneylau/components/web-server/global/db"
	"gitee.com/cheneylau/components/web-server/model"
	"github.com/cheneylew/gotools/tool"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"github.com/prometheus/common/log"
)

func User(c *gin.Context) {
	res, err := controller.BaseListData(c)
	defer controller.EchoJsonList(c, res, err)
	method := c.Request.Method
	log.Info(method)
	switch method {
	case "GET":
		var users []model.User
		db.DB.Find(&users)
		items, err1 := tool.ArrToInterfaces(users)
		if err1 != nil {
			*err = err1
			return
		}
		res.Data = items
	case "POST":
		var user model.User
		err1 := c.BindJSON(&user)
		if err1 != nil {
			*err = err1
			return
		}
		db.DB.Create(&user)
	case "PUT":
		var newUserInfo model.User
		err1 := c.BindJSON(&newUserInfo)
		if err1 != nil {
			*err = err1
			return
		}

		id := c.Param("id")
		var user model.User
		db.DB.Find(&user, id)
		copier.CopyWithOption(&user, &newUserInfo, copier.Option{IgnoreEmpty: true, DeepCopy: true})
		db.DB.Save(&user)
		log.Info(id)
	case "DELETE":
		id := c.Param("id")
		db.DB.Delete(&model.User{}, id)
	}
}
